package com.whpu.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * Created by RiceBall on 2020/10/1 22:04
 */
@Controller
@RequestMapping("/file")
public class FileController {
    @RequestMapping("/upload")
    public String fileupload(@RequestParam("file") MultipartFile upload) throws Exception {
        return "redirect:" + uploadImageOss(upload);
    }

    /**
     * 上传文件到oos
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String uploadImageOss(MultipartFile file) throws Exception {
        // Endpoint以北京为例，其它Region请按实际情况填写。
        String endpoint = "https://image.xiaovcloud.cn";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAI4GAQrraHuFmY8dNGSh7m";
        String accessKeySecret = "1eQBSb48U3hroi3qN63nMbH7a9v7rX";
        //创建的bucket名
        String bucketName = "xiaovcloud";
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //使用uuid作为文件名防止重复
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        String fileName = uuid + "." + substring;

        final File tempFile = File.createTempFile(uuid, substring);
        //MultipartFile  转换为 File
        file.transferTo(tempFile);
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        String fileUrl;
        String fileHost = "upload";
        try {
            //创建文件路径
            fileUrl = fileHost + "/" + fileName;
            ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, tempFile));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        } finally {
            //关闭
            ossClient.shutdown();
            //删除临时生成的文件
            if (tempFile.exists()) {
                tempFile.delete();
            }

        }
        return endpoint + "/" + fileUrl;
    }
}
